<?php

namespace App\Service\UserService;

use App\Model\PssModel\PddGoods;
use App\Model\PssModel\PddToken;
use App\Model\PssModel\YouzanGoods;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\VendorClient\PddApi\ShopOutCloundPddApiClient;
use Hyperf\Utils\WaitGroup;

class PddService extends BaseService
{
    private $client;

    /**
     * 接收消息数据
     * @param string $messageType
     * @param array $data
     */
    public function MessageRev(string $messageType, array $goodsList, array $binfo)
    {
        $shopInfoObj = PddToken::instance()->where('status', 1)->where('auth_type', 26)
            ->where('bid', $binfo['bid'])->first();

        if (empty($shopInfoObj)) {
            return Normal::returnCode(Normal::FAIL, '未找到店铺信息');
        }

        $shopInfo = $shopInfoObj->toArray();

        $this->client = new ShopOutCloundPddApiClient($shopInfo);

        // if ($messageType == 'goodsSkuChange') {
        //     return $this->goodsSkuChange($goodsList['skuList'], $shopInfo);
        // }

        // if ($messageType == 'goodsBatchDown') {
        //     return $this->goodsBatchDown($shopInfo);
        // }

        if ($messageType == 'goodsChange') {
            return $this->goodsChange($goodsList, $shopInfo);
        }

        return Normal::returnCode(Normal::FAIL, '不支持的方法');
    }

    public function goodsBatchDown($shop)
    {
        //处理下架
        $goodsIdListData = PddGoods::instance()
            ->select(['pdd_goods_id', 'skucode'])
            ->where('bid', $shop['bid'])
            ->get()
            ->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的商品idList');
        }
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);
        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            // $result_update = [];
            foreach ($goodsIdList as $goods) {
                co(function () use ($wg, $goods, &$result_update) {
                    $response = $this->client->updateGoodsStatusDown([
                        'goods_id'=>$goods['pdd_goods_id']
                    ]);
                    // $result_update[] = $response;
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }

    public function goodsSkuChange($skuCodes, $shop)
    {
        //处理下架
        $goodsIdListData = PddGoods::instance()
            ->whereIn('skucode', $skuCodes)
            ->select(['pdd_goods_id', 'skucode'])
            ->where('bid', $shop['bid'])
            ->get()
            ->toArray();
        if (empty($goodsIdListData)) {
            return Normal::returnCode(Normal::FAIL, '无匹配的商品idList');
        }
        $goodsIdsTotalList = array_chunk($goodsIdListData, 50);
        //50个一组调用协程
        foreach ($goodsIdsTotalList as $goodsIdList) {
            $count = count($goodsIdList);
            $wg = new WaitGroup();
            $wg->add($count);
            // $result_update = [];
            foreach ($goodsIdList as $goods) {
                co(function () use ($wg, $goods, &$result_update) {
                    $response = $this->client->updateGoodsStatusDown([
                        'goods_id'=>$goods['pdd_goods_id']
                    ]);
                    // $result_update[] = $response;
                    $wg->done();
                });
            }
            $wg->wait();
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }

    public function goodsChange($goodsList, $shop)
    {
        //查询数据
        $goodsChangeList = [];
        foreach ($goodsList as $goodsItem) {
            $skuList = current($goodsItem['skuList']);
            $storeList = current($skuList['storeList']);
            $batchInfo = current($storeList['goods_batch_list']);
            $specInfo = current($batchInfo['spec_list']);
            $skuCode = $batchInfo['supplier_skucode'];
            //拼装商品数组
            $goodsChangeList[$skuCode] = [
                'skucode' => $skuCode,
                'quantity' => $batchInfo['num'],
                'price' => $specInfo['price'],
                'origin_price' => $specInfo['priceMarket'],
                'title' => $goodsItem['goodsName'],
                'costPrice' => $specInfo['priceSettlement'],
                'goods_type' => $goodsItem['goodsType'],
                'images' => $goodsItem['images'],
            ];
        }
        $skuCodeArr = array_keys($goodsChangeList);
        $authSkuGoods = PddGoods::instance()->whereIn('skucode', $skuCodeArr)->where('bid', $shop['bid'])->get()->toArray();

        //这里需要判断是否已存在数据
        $pddGoodsMap = array_column($authSkuGoods, NULL, 'skucode');
        $pddIsExistGoodsSkuCode = array_keys($pddGoodsMap);
        $insertMysqlDatas = [];

        $count = count($goodsChangeList);
        $wg = new WaitGroup();
        $wg->add($count);
        //判断是否已经存在有赞平台
        foreach ($goodsChangeList as $goodsChange) {
            //协程处理
            co(function () use ($wg, $goodsChange,$pddIsExistGoodsSkuCode,$pddGoodsMap,$shop, &$result_update,&$insertMysqlDatas) {
                if (in_array($goodsChange['skucode'], $pddIsExistGoodsSkuCode)) {
                    //修改商品
                    $this->editGoods($goodsChange, $pddGoodsMap[$goodsChange['skucode']], $shop);
                    //上架商品
                    $this->client->updateGoodsStatusUp([
                        'goods_id'=>$pddGoodsMap[$goodsChange['skucode']]['pdd_goods_id']
                    ]);
                } else {
                    //新增商品
                    $insertResult = $this->insertGoods($goodsChange);
                    if ($insertResult['code'] == Normal::SUC) {
                        $insertMysqlDatas[] = [
                            'skucode'       => $goodsChange['skucode'],
                            'pdd_goods_id'  => $insertResult['data']['goods_id'],
                            'bid'           => $shop['bid']
                        ];
                    }
                }
                // $result_update[] = $response;
                $wg->done();
            });
        }


        //判断是否有需要添加的数据
        if (!empty($insertMysqlDatas)) {
            PddGoods::instance()->insert($insertMysqlDatas);
        }

        return Normal::returnCode(Normal::SUC, '处理完成');
    }

    private function insertGoods($goods)
    {
        $data = [
            'cat_id'         => 18491,
            'out_goods_id'   => $goods['skucode'],
            'goods_name'     => $goods['title'],
            // 'sku_list'       => json_encode([
            //     [
            //         'is_onsale' => 1,
            //         'limit_quantity' => 999, //sku购买限制，只入参999
            //         'price' => (float)$goods['price'],
            //         'multi_price' => (float)$goods['price'],
            //         'quantity' => $goods['quantity'],
            //         'spec_id_list'=> [943]
            //     ]
            // ], JSON_UNESCAPED_UNICODE)
        ];
        return $this->client->insertGoods($data);
    }

    /**
     * 更新商品
     * @param array $goodsInfo
     * @param array $pddGoods
     */
    public function editGoods($goods, $pddGoods)
    {
        $data = [
            'goods_id'  => $pddGoods['pdd_goods_id'],
            'outer_id'  => $goods['skucode'],
            'quantity'  => $goods['quantity'],
        ];
        return $this->client->editGoods($data);
    }

    public function orderAfterSale($params)
    {
        return Normal::returnCode(Normal::SUC, '售后成功');
    }
}
